<template>
  <div class="manager-details">
    <div class="page-header">
      <div class="header-title">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          {{ isDetailView ? '返回列表' : '返回仪表盘' }}
        </el-button>
        <h1>{{ isDetailView ? (singleManagerDetail?.manager?.fullName ? singleManagerDetail.manager.fullName + ' 的详细信息' : '加载中...') : '客户经理完成情况' }}</h1>
        <p class="subtitle">{{ isDetailView ? '查看客户经理的详细工作情况和客户分配' : '详细查看所有客户经理的工作完成情况和绩效分析' }}</p>
      </div>
    </div>

    <!-- 单个客户经理详情视图 -->
    <template v-if="isDetailView && singleManagerDetail">
      <!-- 客户经理基本信息卡片 -->
      <div class="overview-cards">
        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleManagerDetail.manager.totalClients }}</div>
              <div class="stat-label">负责客户数</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleManagerDetail.manager.completedTasks }}</div>
              <div class="stat-label">已完成任务</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon warning">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleManagerDetail.manager.totalTasks }}</div>
              <div class="stat-label">总任务数</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon completion">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ singleManagerDetail.manager.completionRate }}%</div>
              <div class="stat-label">完成率</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 服务项目进度 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              服务项目完成情况
            </h2>
            <p class="section-desc">该客户经理负责的各项服务的完成进度</p>
          </div>
        </template>
        
        <el-table 
          :data="singleManagerDetail.serviceStats" 
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="serviceName" label="服务项目" width="200">
            <template #default="scope">
              <div class="service-name">{{ scope.row.serviceName }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="totalTasks" label="总任务数" width="100" align="center" />
          <el-table-column prop="completedTasks" label="已完成" width="100" align="center" />
          <el-table-column prop="completionRate" label="完成率" width="150" align="center">
            <template #default="scope">
              <el-progress 
                :percentage="scope.row.completionRate" 
                :status="scope.row.completionRate < 30 ? 'exception' : scope.row.completionRate < 70 ? 'warning' : 'success'"
                :stroke-width="8"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 最近工作日志 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              最近工作日志
            </h2>
            <p class="section-desc">最近完成的工作记录</p>
          </div>
        </template>
        
        <el-table 
          :data="singleManagerDetail.recentWorkLogs" 
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="clientName" label="客户名称" width="150" />
          <el-table-column prop="clientCode" label="客户代码" width="120" />
          <el-table-column prop="serviceName" label="服务项目" width="150" />
          <el-table-column prop="completionDate" label="完成日期" width="120" align="center" />
          <el-table-column prop="notes" label="备注" />
          <el-table-column prop="createdAt" label="创建时间" width="120" align="center" />
        </el-table>
      </el-card>
    </template>

    <!-- 客户经理列表视图 -->
    <template v-else>
      <!-- 总体统计概览 -->
      <div class="overview-cards">
      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ managerStats.totalManagers }}</div>
            <div class="stat-label">总客户经理数</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon active">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ managerStats.activeManagers }}</div>
            <div class="stat-label">活跃客户经理</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon warning">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ managerStats.underperformingManagers }}</div>
            <div class="stat-label">进度落后经理</div>
          </div>
        </div>
      </el-card>

      <el-card class="overview-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon completion">
            <el-icon><Trophy /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ managerStats.avgCompletionRate }}%</div>
            <div class="stat-label">平均完成率</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 进度落后的客户经理 -->
    <el-card class="section-card" shadow="never" v-if="underperformingManagers.length > 0">
      <template #header>
        <div class="section-header">
          <h2>
            <el-icon class="header-icon warning"><Warning /></el-icon>
            进度落后的客户经理 (后10%)
          </h2>
          <p class="section-desc">以下客户经理的工作完成情况需要重点关注</p>
        </div>
      </template>
      
      <el-table 
        :data="underperformingManagers" 
        style="width: 100%"
        :default-sort="{ prop: 'completionRate', order: 'ascending' }"
      >
        <el-table-column prop="fullName" label="客户经理" width="150">
          <template #default="scope">
            <div class="manager-info">
              <el-avatar :size="32" class="manager-avatar">
                {{ scope.row.fullName.charAt(0) }}
              </el-avatar>
              <span class="manager-name">{{ scope.row.fullName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignedClients" label="分配客户数" width="120" align="center" />
        <el-table-column prop="completedTasks" label="已完成任务" width="120" align="center" />
        <el-table-column prop="totalTasks" label="总任务数" width="120" align="center" />
        <el-table-column prop="completionRate" label="完成率" width="120" align="center" sortable>
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.completionRate" 
              :status="scope.row.completionRate < 30 ? 'exception' : scope.row.completionRate < 70 ? 'warning' : 'success'"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastActivityDate" label="最后活动时间" width="150" align="center" />
        <el-table-column prop="performanceRank" label="绩效排名" width="100" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.performanceRank <= 3 ? 'success' : scope.row.performanceRank <= managerStats.totalManagers * 0.7 ? 'warning' : 'danger'"
              size="small"
            >
              第{{ scope.row.performanceRank }}名
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="viewManagerDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 所有客户经理列表 -->
    <el-card class="section-card" shadow="never">
      <template #header>
        <div class="section-header">
          <div class="header-left">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              所有客户经理完成情况
            </h2>
            <p class="section-desc">查看所有客户经理的详细工作统计</p>
          </div>
          <div class="header-right">
            <el-input
              v-model="searchQuery"
              placeholder="搜索客户经理姓名"
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table 
        :data="filteredManagerList" 
        style="width: 100%"
        v-loading="loading"
        :default-sort="{ prop: 'completionRate', order: 'descending' }"
      >
        <el-table-column prop="fullName" label="客户经理" width="150" fixed="left">
          <template #default="scope">
            <div class="manager-info">
              <el-avatar :size="32" class="manager-avatar">
                {{ scope.row.fullName.charAt(0) }}
              </el-avatar>
              <span class="manager-name">{{ scope.row.fullName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignedClients" label="分配客户数" width="120" align="center" sortable />
        <el-table-column prop="completedTasks" label="已完成任务" width="120" align="center" sortable />
        <el-table-column prop="totalTasks" label="总任务数" width="120" align="center" sortable />
        <el-table-column prop="completionRate" label="完成率" width="150" align="center" sortable>
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.completionRate" 
              :status="scope.row.completionRate < 30 ? 'exception' : scope.row.completionRate < 70 ? 'warning' : 'success'"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="avgDaysPerTask" label="平均任务用时(天)" width="150" align="center" sortable />
        <el-table-column prop="lastActivityDate" label="最后活动时间" width="150" align="center" sortable />
        <el-table-column prop="performanceRank" label="绩效排名" width="100" align="center" sortable>
          <template #default="scope">
            <el-tag 
              :type="scope.row.performanceRank <= 3 ? 'success' : scope.row.performanceRank <= managerStats.totalManagers * 0.7 ? 'warning' : 'danger'"
              size="small"
            >
              第{{ scope.row.performanceRank }}名
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewManagerDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  User,
  CircleCheck,
  Warning,
  Trophy,
  List,
  Search
} from '@element-plus/icons-vue';
import { trpc } from '../../utils/trpc';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const searchQuery = ref('');

// 判断是否为单个客户经理详情页面
const isDetailView = computed(() => !!route.params.id);
const managerId = computed(() => isDetailView.value ? Number(route.params.id) : null);

// 客户经理总体统计
const managerStats = ref({
  totalManagers: 0,
  activeManagers: 0,
  underperformingManagers: 0,
  avgCompletionRate: 0,
});

// 进度落后的客户经理列表
const underperformingManagers = ref([]);

// 所有客户经理列表
const managerList = ref([]);

// 单个客户经理详情数据
const singleManagerDetail = ref(null);

// 过滤后的客户经理列表
const filteredManagerList = computed(() => {
  if (!searchQuery.value) {
    return managerList.value;
  }
  return managerList.value.filter(manager => 
    manager.fullName.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 返回按钮逻辑
const goBack = () => {
  if (isDetailView.value) {
    router.push('/manager-details');
  } else {
    router.push('/dashboard');
  }
};

// 查看客户经理详情
const viewManagerDetail = (manager) => {
  router.push(`/manager-details/${manager.id}`);
};

// 加载客户经理数据
const loadManagerData = async () => {
  loading.value = true;
  try {
    if (isDetailView.value && managerId.value) {
      // 加载单个客户经理详情
      console.log('开始加载单个客户经理详情，ID:', managerId.value);
      const result = await trpc.stats.managerDetail.query({ managerId: managerId.value });

      console.log('单个经理详情API返回结果:', result);

      if (result.success && result.data) {
        singleManagerDetail.value = result.data;
        console.log('单个客户经理详情加载成功:', result.data);
        ElMessage.success('客户经理详情加载成功');
      } else {
        console.error('获取客户经理详情失败:', result.message);
        ElMessage.error(result.message || '获取客户经理详情失败');
      }
    } else {
      // 加载客户经理列表数据
      console.log('开始加载客户经理数据...');
      const result = await trpc.stats.managerDetails.query({});

      console.log('API返回结果:', result);

      if (result.success && result.data) {
        managerStats.value = result.data.stats;
        underperformingManagers.value = result.data.underperformingManagers;
        managerList.value = result.data.allManagers;
        
        console.log('客户经理数据加载成功:', result.data);
        ElMessage.success('客户经理数据加载成功');
      } else {
        console.error('获取客户经理数据失败:', result.message);
        ElMessage.error(result.message || '获取客户经理数据失败');
      }
    }
  } catch (error) {
    console.error('加载客户经理数据失败:', error);
    ElMessage.error('加载数据失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadManagerData();
});
</script>

<style scoped>
.manager-details {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.header-title h1 {
  margin: 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #262626;
}

.back-btn {
  font-size: 14px;
  padding: 0;
  margin-bottom: 8px;
  color: #1890ff;
}

.back-btn:hover {
  color: #40a9ff;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 16px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.overview-card {
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-icon.completion {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.section-card {
  margin-bottom: 32px;
  border-radius: 12px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left h2, .section-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
}

.header-icon.warning {
  color: #faad14;
}

.section-desc {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.manager-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.manager-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.manager-name {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .manager-details {
    padding: 16px;
  }
  
  .overview-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}
</style>